package com.sinszm.web.socket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * WebSocket参数拦截组装
 *
 * @author chenjianbo
 */
public class MWebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(
            ServerHttpRequest request,
            ServerHttpResponse response,
            WebSocketHandler wsHandler,
            @Nullable Map<String, Object> attributes) throws Exception {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        Map<String, String[]> params = servletRequest.getParameterMap();
        if (params != null && !params.isEmpty()) {
            params.forEach((k, v) -> {
                String value = v == null || v.length == 0 ? "" : String.join(",", v);
                assert attributes != null;
                attributes.put(k, value);
            });
        }
        assert attributes != null;
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

}
